import type { SiteConfig, UserSiteConfig } from '../../types'
import { webcrypto } from 'node:crypto'
import { consola } from 'consola'
import { colors } from 'consola/utils'
import { options as floatingVueOptions } from 'floating-vue'
import { countPerformanceTime } from '../utils/performance'
import { loadConfigFromFile } from './utils'

export const defaultSiteConfig: SiteConfig = {
  mode: 'auto',
  url: '/',
  lang: 'en',
  languages: ['en', 'zh-CN'],
  timezone: '',
  title: 'Valaxy Blog',
  description: 'A blog generated by Valaxy.',
  subtitle: 'Next Generation Static Blog Framework.',
  author: {
    avatar: 'https://valaxy.site/valaxy-logo.png',
    email: 'i@valaxy.site',
    link: 'https://valaxy.site',
    name: 'VALAXY Developer',
    status: {
      emoji: '🌌',
      message: 'The moonlight is beautiful.',
    },
  },
  favicon: '/favicon.svg',
  feed: {
    name: '',
    favicon: '/favicon.svg',
  },
  social: [],

  orderBy: 'date',
  lastUpdated: false,

  license: {
    enabled: true,
    language: '',
    type: 'by-nc-sa',
  },

  sponsor: {
    enable: true,
    description: '这是关于赞助的一些描述',
    methods: [],
  },

  search: {
    enable: false,
    provider: 'fuse',
  },
  fuse: {
    dataPath: 'valaxy-fuse-list.json',
    options: {
      keys: [],
    },
  },

  comment: {
    enable: false,
  },

  frontmatter: {
    time_warning: 180 * 24 * 60 * 60 * 1000,
  },

  cdn: {
    prefix: 'https://unpkg.com/',
  },

  mediumZoom: {
    enable: false,
    selector: '',
    options: {},
  },

  vanillaLazyload: {
    enable: false,
    options: {},
  },

  floatingVue: floatingVueOptions,

  statistics: {
    enable: false,
    readTime: {
      speed: {
        cn: 300,
        en: 100,
      },
    },
  },

  pageSize: 7,

  encrypt: {
    enable: false,
    algorithm: 'AES-CBC',
    salt: webcrypto.getRandomValues(new Uint8Array(16)),
    iv: webcrypto.getRandomValues(new Uint8Array(16)),
  },

  redirects: {
    useVueRouter: true,
    rules: [],
  },
}

/**
 * Type helper for site.config.ts
 * @param config
 */
export function defineSiteConfig(config: UserSiteConfig) {
  return config
}

/**
 * resolve valaxy config from special root
 */
export async function resolveSiteConfigFromRoot(root: string) {
  return loadConfigFromFile<UserSiteConfig>('site', {
    cwd: root,
  })
}

/**
 * resolve site.config.ts and merge with default
 * @param root
 */
export async function resolveSiteConfig(root: string) {
  const endCount = countPerformanceTime()
  const { config: userSiteConfig, configFile: siteConfigFile } = await resolveSiteConfigFromRoot(root)
  const duration = endCount()

  if (userSiteConfig && siteConfigFile)
    consola.success(`Resolve ${colors.cyan('siteConfig')} from ${colors.dim(siteConfigFile)} ${colors.yellow(duration)}`)

  return {
    siteConfig: userSiteConfig,
    siteConfigFile,
  }
}
